import mysql from 'mysql2/promise';

// 简单的数据库配置
const config = {
  host: 'localhost',
  user: 'root',
  password: '159159',  // 请修改为你的密码
  database: 'testdb',
  port: 3306,
};

// 创建连接
let connection: mysql.Connection | null = null;

// 获取数据库连接
async function getConnection() {
  if (!connection) {
    try {
      connection = await mysql.createConnection(config);
      console.log('MySQL连接成功');
    } catch (error) {
      console.error('MySQL连接失败:', error);
      throw error;
    }
  }
  return connection;
}

// 简单的SELECT查询
export async function select(query: string, params: any[] = []): Promise<any[]> {
  try {
    const conn = await getConnection();
    const [rows] = await conn.execute(query, params);
    return Array.isArray(rows) ? rows : [];
  } catch (error) {
    console.error('查询失败:', error);
    throw error;
  }
}

// 关闭连接
export async function closeConnection() {
  if (connection) {
    await connection.end();
    connection = null;
    console.log('MySQL连接已关闭');
  }
}